package com.hly.versioncontroladmin.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hly.versioncontroladmin.domain.Bo.VcVersionBo;
import com.hly.versioncontroladmin.domain.Bo.VersionCheckBo;
import com.hly.versioncontroladmin.domain.VcApplication;
import com.hly.versioncontroladmin.domain.VcVersion;
import com.hly.versioncontroladmin.domain.Vo.VersionCheckVo;
import com.hly.versioncontroladmin.mapper.VcApplicationMapper;
import com.hly.versioncontroladmin.mapper.VcVersionMapper;
import com.hly.versioncontroladmin.result.Code;
import com.hly.versioncontroladmin.result.PageQuery;
import com.hly.versioncontroladmin.service.VcVersionService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class VcVersionServiceImpl extends ServiceImpl<VcVersionMapper, VcVersion> implements VcVersionService {

    private final VcApplicationMapper applicationMapper;

    @Override
    public Page<VcVersion> listQuery(PageQuery<VcVersion> pageQuery, VcVersionBo bo) {
        Page<VcVersion> page = buildQueryWrapper(bo).page(pageQuery.builderPage());
        return page;
    }

    @Override
    public VcVersion getNewAppVersion(String appId) {
        return getNewAppVersion(appId, null);
    }

    @Override
    public VcVersion getNewAppVersion(String appId, Integer isShow) {
        return lambdaQuery()
                .eq(VcVersion::getAppId, appId)
                .eq(isShow != null, VcVersion::getIsShow, isShow)
                .orderByDesc(VcVersion::getVcVersion)
                .last("limit 0,1")
                .one();
    }

    @Override
    public VersionCheckVo check(VersionCheckBo bo) {

        VcApplication application = applicationMapper.selectById(bo.getAppId());

        if (application == null){
            Code.BUSINESS_ERR("该应用不存在");
        }

        VcVersion newAppVersion = getNewAppVersion(bo.getAppId(), 1);

        if (newAppVersion == null){
            VersionCheckVo.builder()
                .params(bo)
                .name(application.getName() + newAppVersion.getSuffix())
                .build();
        }

        return VersionCheckVo.builder()
                .params(bo)
                .version(newAppVersion)
                .name(application.getName() + newAppVersion.getSuffix())
                .isNew(!newAppVersion.getVcVersion().equals(bo.getIgnoreVersion()) &&
                    bo.getVersion() < newAppVersion.getVcVersion())
                .build();
    }

    public LambdaQueryChainWrapper<VcVersion> buildQueryWrapper(VcVersionBo bo){
        LambdaQueryChainWrapper<VcVersion> queryChainWrapper = lambdaQuery()
                .eq(bo.getAppId() != null, VcVersion::getAppId, bo.getAppId());
        return queryChainWrapper;
    }

}
